package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: 登录接口
 * @author: chengbaiyi
 * @create: 2022-06-25 20:22
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String data = "";
        String msg = "未知错误";
        // 得到前端参数并进行校验
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String isadmin = req.getParameter("isadmin");
        if (!StrUtil.isBlank(username) && !StrUtil.isBlank(password)) {
            // 请求数据库验证用户名和密码
            Connection connection = DBUtil.getConnection();
            String sql = "select * from userinfo where username=? and password=?";
            if (!StrUtil.isBlank(isadmin) && isadmin.equals("1")) {
                // 管理员登录
                sql += " and isadmin=1";
            }
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, MD5.create().digestHex(password));
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 用户名和密码正确
                state = 200;
                data = username;
                msg = "登录成功！";
                // 将当前登录用户保存到session中
                HttpSession session = req.getSession(true);
                UserInfo userInfo = new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                session.setAttribute(ApplicationVariable.SESSION_USER_KEY, userInfo);
            } else {
                msg = "用户名或密码错误！";
            }
        } else {
            msg = "非法参数！";
        }
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        ResultData resultData = new ResultData(state, data, msg);
        resp.getWriter().println(JSONUtil.toJsonStr(resultData));
    }
}
